package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.excel.entity.Exceel;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.common.security.auth.AuthLogic;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.vo.RolePerm;
import com.ruoyi.system.mapper.*;
import com.ruoyi.tableConfig.api.RemoteRoleTableService;
import com.ruoyi.tableConfig.api.RemoteTableService;
import com.ruoyi.tableConfig.api.RemoteUserTableService;
import com.ruoyi.tableConfig.api.domain.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.api.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysRoleService;

import javax.servlet.http.HttpServletResponse;

/**
 * 角色 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private RemoteRoleTableService remoteRoleTableService;

    @Autowired
    private RemoteTableService remoteTableService;

    @Autowired
    private RemoteUserTableService remoteUserTableService;

    @Autowired
    private SysMenuServiceImpl sysMenuService;

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysRole> selectRoleList(SysRole role) {
        List<SysRole> sysRoles = roleMapper.selectRoleList(role);
        sysRoles.forEach(v -> {
            if (v.getRoleId() == AuthLogic.SUPER_ADMIN_ID) {//管理员角色
                Set<String> perms = new HashSet<String>();
                perms.add(AuthLogic.ALL_PERMISSION);
                v.setPermissions(perms);
            } else {
                Set<String> rolePerms = sysMenuService.selectMenuPermsByRoleId(v.getRoleId());
                v.setPermissions(rolePerms);
            }
        });
        return sysRoles;
    }

    /**
     * 根据条件查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleListPerm(SysRole role) {
        List<SysRole> sysRoles = roleMapper.selectRoleList(role);
        List<RolePerm> rolePerms = sysMenuService.selectMenuPermsAllRole();
        sysRoles.forEach(v -> {
            if (v.getRoleId() == AuthLogic.SUPER_ADMIN_ID) {//管理员角色
                Set<String> perms = new HashSet<String>();
                perms.add(AuthLogic.ALL_PERMISSION);
                v.setPermissions(perms);
            } else {
                Set<String> permsSet = new HashSet<>();
                rolePerms.forEach(m -> {
                    if (null != m && null != m.getRoleId() && m.getRoleId().equals(v.getRoleId()) && null != m.getPerms()) {
                        permsSet.add(m.getPerms());
                    }
                });
                v.setPermissions(permsSet);
            }
        });
        return sysRoles;
    }

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
//    @DataScope(deptAlias = "d")
    public TableDataInfo<SysRole> selectRolePage(SysRole role, PageQuery pageQuery) {
        IPage<SysRole> page = roleMapper.selectRolePage(pageQuery.build(), role);
        page.getRecords().forEach(v -> {
            if (v.getRoleId() == AuthLogic.SUPER_ADMIN_ID) {
                Set<String> perms = new HashSet<String>();
                perms.add(AuthLogic.ALL_PERMISSION);
                v.setPermissions(perms);
            } else {
                Set<String> rolePerms = sysMenuService.selectMenuPermsByRoleId(v.getRoleId());
                v.setPermissions(rolePerms);
            }
        });
        return TableDataInfo.build(page);
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     * @author zly
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        return userRoles;
    }

    @Override
    public List<SysRole> selectRoleByUserId(Long userId) {
        List<SysRole> sysRoles = roleMapper.selectRolePermissionByUserId(userId);
        sysRoles.forEach(v -> {
            if (v.getRoleId() == AuthLogic.SUPER_ADMIN_ID) {
                Set<String> perms = new HashSet<String>();
                perms.add(AuthLogic.ALL_PERMISSION);
                v.setPermissions(perms);
            } else {
                Set<String> rolePerms = sysMenuService.selectMenuPermsByRoleId(v.getRoleId());
                v.setPermissions(rolePerms);
            }
        });
        return sysRoles;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll() {
        return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId) {
        SysRole sysRole = roleMapper.selectRoleById(roleId);
        if (sysRole.getRoleId() == AuthLogic.SUPER_ADMIN_ID) {
            Set<String> perms = new HashSet<String>();
            perms.add(AuthLogic.ALL_PERMISSION);
            sysRole.setPermissions(perms);
        } else {
            Set<String> rolePerms = sysMenuService.selectMenuPermsByRoleId(sysRole.getRoleId());
            sysRole.setPermissions(rolePerms);
        }
        return sysRole;
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleId 角色id
     */
    @Override
    public void checkRoleDataScope(Long roleId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysRole role = new SysRole();
            role.setRoleId(roleId);
            List<SysRole> roles = SpringUtils.getAopProxy(this).selectRoleList(role);
            if (StringUtils.isEmpty(roles)) {
                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRole(SysRole role) {
        // 新增角色信息
        roleMapper.insertRole(role);
        return insertRoleMenu(role);
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRole(SysRole role) {
        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        return insertRoleMenu(role);
    }

    /**
     * 修改角色状态
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRoleStatus(SysRole role) {
        return roleMapper.updateRole(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int authDataScope(SysRole role) {
        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 从角色表格同步到用户
     *
     * @return
     */
    @Override
    public void syncUser(Long roleId) {
        //查询角色下的用户
        List<SysUserRole> sysUserRoles = userRoleMapper.selectUserRoleByRoleId(roleId);
        //查询角色表格
        R<List<SysRoleTable>> sysRoleTableList = remoteRoleTableService.getRoleTableInfoByRoleId(roleId, SecurityConstants.INNER);
        if (null != sysRoleTableList.getData() && sysRoleTableList.getData().size() > 0) {
            for (SysUserRole sysUserRole : sysUserRoles) {
                for (SysRoleTable sysRoleTable : sysRoleTableList.getData()) {
                    //查询角色表格列
                    R<List<SysRoleTableColumn>> sysRoleTableColumnList = remoteRoleTableService.getColumnInfoByRoleTableId(sysRoleTable.getRoleTableId(), SecurityConstants.INNER);
                    //查询用户表格列
                    SysUserTableColumn sysUserTableColumn = new SysUserTableColumn();
                    sysUserTableColumn.setRoleTableId(sysRoleTable.getRoleTableId());
                    sysUserTableColumn.setUserId(sysUserRole.getUserId());
                    R<List<SysUserTableColumn>> sysUserTableColumnList = remoteUserTableService.getUserColumnInfo(sysUserTableColumn, SecurityConstants.INNER);

                    if (sysUserTableColumnList.getCode() == 200) {
                        //用户表格列中的角色表格id
                        List<Long> userTableList = new ArrayList<>();
                        if (null != sysUserTableColumnList.getData() && sysUserTableColumnList.getData().size() > 0) {
                            for (SysUserTableColumn userTableColumn : sysUserTableColumnList.getData()) {
                                userTableList.add(userTableColumn.getColumnId());
                            }
                        }
                        //更新用户表格列
                        if (null != sysRoleTableColumnList.getData() && sysRoleTableColumnList.getData().size() > 0) {
                            for (SysRoleTableColumn sysRoleTableColumn : sysRoleTableColumnList.getData()) {
                                if (!(userTableList.indexOf(sysRoleTableColumn.getRoleColumnId()) > -1)) {
                                    SysUserTableColumn userTableColumn = new SysUserTableColumn();
                                    BeanUtils.copyProperties(sysRoleTableColumn, userTableColumn);
                                    userTableColumn.setUserId(sysUserRole.getUserId());
                                    userTableColumn.setColumnId(sysRoleTableColumn.getRoleColumnId());
                                    remoteUserTableService.userTableColumnAdd(userTableColumn, SecurityConstants.INNER);
                                }
                            }
                        }
                    }

                    //查询表单
                    R<SysRoleTableForm> sysRoleTableForm = remoteRoleTableService.getRoleFormInfoByRoleTableId(sysRoleTable.getRoleTableId(), SecurityConstants.INNER);
                    if (null != sysRoleTableForm.getData()) {
                        R<List<SysRoleTableFormItem>> sysRoleTableFormItemList = remoteRoleTableService.getRoleItemInfoByFormId(sysRoleTableForm.getData().getRoleFormId(), SecurityConstants.INNER);
                        //用户表单项
                        SysUserTableFormItem sysUserTableFormItem = new SysUserTableFormItem();
                        sysUserTableFormItem.setUserId(sysUserRole.getUserId());
                        sysUserTableFormItem.setRoleFormId(sysRoleTableForm.getData().getRoleFormId());
                        R<List<SysUserTableFormItem>> sysUserTableFormItemList = remoteUserTableService.getFormItemInfo(sysUserTableFormItem, SecurityConstants.INNER);

                        if (sysUserTableFormItemList.getCode() == 200) {
                            //用户表单项
                            List<Long> userTableItem = new ArrayList<>();
                            if (null != sysUserTableFormItemList.getData() && sysUserTableFormItemList.getData().size() > 0) {
                                for (SysUserTableFormItem userTableFormItem : sysUserTableFormItemList.getData()) {
                                    userTableItem.add(userTableFormItem.getItemId());
                                }
                            }
                            //更新用户表单项
                            if (null != sysRoleTableFormItemList.getData() && sysRoleTableFormItemList.getData().size() > 0) {
                                for (SysRoleTableFormItem sysRoleTableFormItem : sysRoleTableFormItemList.getData()) {
                                    if (!(userTableItem.indexOf(sysRoleTableFormItem.getRoleItemId()) > -1)) {
                                        SysUserTableFormItem userTableFormItem = new SysUserTableFormItem();
                                        BeanUtils.copyProperties(sysRoleTableFormItem, userTableFormItem);
                                        userTableFormItem.setItemId(sysRoleTableFormItem.getRoleItemId());
                                        userTableFormItem.setUserId(sysUserRole.getUserId());
                                        remoteUserTableService.userTableFormItemAdd(userTableFormItem, SecurityConstants.INNER);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        insertRoleTable(role);
        return rows;
    }

    /**
     * 初始化角色表格配置
     *
     * @param role
     * @return
     */
    public void insertRoleTable(SysRole role) {
        List<Long> menuIds = new ArrayList<>();
        menuIds.addAll(Arrays.asList(role.getMenuIds()));
        List<SysMenu> sysMenuList = sysMenuMapper.selectMenuByMenuIdIn(menuIds);
        R<List<SysRoleTable>> sysRoleTableList = remoteRoleTableService.getRoleTableInfoByRoleId(role.getRoleId(), SecurityConstants.INNER);
        String userName = SecurityUtils.getUsername();
        Long userId = SecurityUtils.getUserId();
        Date date = new Date();
        List<Long> sysMenuIds = new ArrayList<Long>();
        List<Map<String, Long>> mapList = new ArrayList<>();
        if (null != sysRoleTableList.getData() && sysRoleTableList.getData().size() > 0) {
            for (SysRoleTable sysRoleTable : sysRoleTableList.getData()) {
                sysMenuIds.add(sysRoleTable.getMenuId());
                Map<String, Long> map = new HashMap<>();
                map.put("menuId", sysRoleTable.getMenuId());
                map.put("tableId", sysRoleTable.getRoleTableId());
                mapList.add(map);
            }
        }
        List<Long> menuIdList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            menuIdList.add(sysMenu.getMenuId());
            if (!(sysMenuIds.indexOf(sysMenu.getMenuId()) > -1)) {
                R<List<SysTable>> sysTableList = remoteTableService.getTableInfoByMenuId(sysMenu.getMenuId(), SecurityConstants.INNER);
                for (SysTable sysTable : sysTableList.getData()) {
                    SysRoleTable sysRoleTable = new SysRoleTable();
                    BeanUtils.copyProperties(sysTable, sysRoleTable);
                    sysRoleTable.setRoleId(role.getRoleId());
                    sysRoleTable.setCreateBy(userId);
                    sysRoleTable.setCreateTime(date);
                    remoteRoleTableService.roleTableAdd(sysRoleTable, SecurityConstants.INNER);
                    Long roleTableId = sysRoleTable.getRoleTableId();
                    //角色表格列配置
                    R<List<SysTableColumn>> sysTableColumnList = remoteTableService.getColumnInfoByTableId(sysTable.getTableId(), SecurityConstants.INNER);
                    for (SysTableColumn sysTableColumn : sysTableColumnList.getData()) {
                        SysRoleTableColumn sysRoleTableColumn = new SysRoleTableColumn();
                        BeanUtils.copyProperties(sysTableColumn, sysRoleTableColumn);
                        sysRoleTableColumn.setRoleTableId(roleTableId);
                        sysRoleTableColumn.setCreateBy(userId);
                        sysRoleTableColumn.setCreateTime(date);
                        remoteRoleTableService.columnAdd(sysRoleTableColumn, SecurityConstants.INNER);
                    }
                    //角色可编辑配置项
                    R<SysTableEditConfig> sysTableEditConfigR = remoteTableService.getEditConfigInfoByTableId(sysTable.getTableId(), SecurityConstants.INNER);
                    SysRoleTableEditConfig sysRoleTableEditConfig = new SysRoleTableEditConfig();
                    BeanUtils.copyProperties(sysTableEditConfigR.getData(), sysRoleTableEditConfig);
                    sysRoleTableEditConfig.setCreateBy(userId);
                    sysRoleTableEditConfig.setCreateTime(date);
                    sysRoleTableEditConfig.setRoleTableId(roleTableId);
                    remoteRoleTableService.editConfigAdd(sysRoleTableEditConfig, SecurityConstants.INNER);
                    //角色校验规则配置
                    R<List<SysTableEditRules>> sysTableEditRulesRList = remoteTableService.getEditRulesInfoByTableId(sysTable.getTableId(), SecurityConstants.INNER);
                    for (SysTableEditRules sysTableEditRules : sysTableEditRulesRList.getData()) {
                        SysRoleTableEditRules sysRoleTableEditRules = new SysRoleTableEditRules();
                        BeanUtils.copyProperties(sysTableEditRules, sysRoleTableEditRules);
                        sysRoleTableEditRules.setCreateBy(userId);
                        sysRoleTableEditRules.setCreateTime(date);
                        sysRoleTableEditRules.setRoleTableId(roleTableId);
                        remoteRoleTableService.roleRuleAdd(sysRoleTableEditRules, SecurityConstants.INNER);
                    }
                    //角色表单配置
                    R<SysTableForm> sysTableFormR = remoteTableService.getFormInfoByTableId(sysTable.getTableId(), SecurityConstants.INNER);
                    SysRoleTableForm sysRoleTableForm = new SysRoleTableForm();
                    BeanUtils.copyProperties(sysTableFormR.getData(), sysRoleTableForm);
                    sysRoleTableForm.setCreateBy(userId);
                    sysRoleTableForm.setCreateTime(date);
                    sysRoleTableForm.setRoleTableId(roleTableId);
                    remoteRoleTableService.roleTableFormAdd(sysRoleTableForm, SecurityConstants.INNER);
                    if (null != sysRoleTableForm.getRoleFormId()) {
                        R<List<SysTableFormItem>> sysTableFormItemRlist = remoteTableService.getFormItemInfoByFormId(sysRoleTableForm.getRoleFormId(), SecurityConstants.INNER);
                        for (SysTableFormItem sysTableFormItem : sysTableFormItemRlist.getData()) {
                            SysRoleTableFormItem sysRoleTableFormItem = new SysRoleTableFormItem();
                            BeanUtils.copyProperties(sysTableFormItem, sysRoleTableFormItem);
                            sysRoleTableFormItem.setCreateBy(userId);
                            sysRoleTableFormItem.setCreateTime(date);
                            sysRoleTableFormItem.setRoleFormId(sysRoleTableForm.getRoleFormId());
                            remoteRoleTableService.roleFormItemAdd(sysRoleTableFormItem, SecurityConstants.INNER);
                        }
                    }
                    //分页配置
                    R<SysTablePager> sysTablePagerR = remoteTableService.getPageInfoByTableId(sysTable.getTableId(), SecurityConstants.INNER);
                    SysRoleTablePager sysRoleTablePager = new SysRoleTablePager();
                    BeanUtils.copyProperties(sysTablePagerR.getData(), sysRoleTablePager);
                    sysRoleTablePager.setCreateBy(userId);
                    sysRoleTablePager.setCreateTime(date);
                    sysRoleTablePager.setRoleTableId(roleTableId);
                    remoteRoleTableService.rolePageAdd(sysRoleTablePager, SecurityConstants.INNER);
                    //代理配置
                    R<SysTableProxy> sysTableProxyR = remoteTableService.getProxyInfoByTableId(sysTable.getTableId(), SecurityConstants.INNER);
                    SysRoleTableProxy sysRoleTableProxy = new SysRoleTableProxy();
                    BeanUtils.copyProperties(sysTableProxyR.getData(), sysRoleTableProxy);
                    sysRoleTableProxy.setCreateBy(userId);
                    sysRoleTableProxy.setCreateTime(date);
                    sysRoleTableProxy.setRoleTableId(roleTableId);
                    remoteRoleTableService.roleProxyAdd(sysRoleTableProxy, SecurityConstants.INNER);
                    //工具栏配置
                    R<SysTableToolbarConfig> sysTableToolbarConfigR = remoteTableService.getToolBarConfigInfoByTableId(sysTable.getTableId(), SecurityConstants.INNER);
                    SysRoleTableToolbarConfig sysRoleTableToolbarConfig = new SysRoleTableToolbarConfig();
                    BeanUtils.copyProperties(sysTableToolbarConfigR.getData(), sysRoleTableToolbarConfig);
                    sysRoleTableToolbarConfig.setCreateBy(userId);
                    sysRoleTableToolbarConfig.setCreateTime(date);
                    sysRoleTableToolbarConfig.setRoleTableId(roleTableId);
                    remoteRoleTableService.roleToolBarAdd(sysRoleTableToolbarConfig, SecurityConstants.INNER);
                }
            }
        }
        //删除角色表格中已存在，在角色授权的去除的表格配置
        List<Long> diffSet = new ArrayList<>();
        for (Long s : sysMenuIds) {
            diffSet.add(s);
        }
        diffSet.removeAll(menuIdList);
        List<Long> roleTableList = new ArrayList<>();
        for (Map map : mapList) {
            for (Long menuId : diffSet) {
                if (map.get("menuId") == menuId) {
                    roleTableList.add((Long) map.get("tableId"));
                }
            }
        }
        Long[] L = roleTableList.stream().toArray(Long[]::new);
        remoteRoleTableService.roleTableRemoves(L, SecurityConstants.INNER);
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds()) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0) {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleById(Long roleId) {
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(roleId);
        return roleMapper.deleteRoleById(roleId);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new SysRole(roleId));
            checkRoleDataScope(roleId);
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDept(roleIds);
        return roleMapper.deleteRoleByIds(roleIds);
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRole userRole) {
        List<Long> userIds = new ArrayList<>();
        userIds.add(userRole.getUserId());
        deleteUserTable(userRole.getRoleId(), userIds.stream().toArray(Long[]::new));
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
        deleteUserTable(roleId, userIds);
        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds) {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        insertUserTable(roleId, userIds);
        return userRoleMapper.batchUserRole(list);
    }

    /**
     * 删除用户表格配置
     *
     * @param roleId  角色id
     * @param userIds 用户id数组
     */
    public void deleteUserTable(Long roleId, Long[] userIds) {
        for (Long userId : userIds) {
            R<List<SysUserTableColumn>> SysUserTableColumnListR = remoteUserTableService.getColumnInfoByUserId(userId, SecurityConstants.INNER);
            if (null != SysUserTableColumnListR.getData() && (SysUserTableColumnListR.getData().size() > 0)) {
                remoteUserTableService.userTableColumnRemoveByUserId(userId, SecurityConstants.INNER);
            }
            R<List<SysUserTableFormItem>> SysUserTableFormItemListR = remoteUserTableService.getFormItemInfoByUserId(userId, SecurityConstants.INNER);
            if (null != SysUserTableFormItemListR.getData() && (SysUserTableFormItemListR.getData().size() > 0)) {
                remoteUserTableService.userTableFormItemRemoveByUserId(userId, SecurityConstants.INNER);
            }
        }
    }

    /**
     * 添加用户表格配置
     *
     * @param roleId
     * @param userIds
     */
    public void insertUserTable(Long roleId, Long[] userIds) {
        R<List<SysRoleTable>> sysRoleTableList = remoteRoleTableService.getRoleTableInfoByRoleId(roleId, SecurityConstants.INNER);
        for (SysRoleTable sysRoleTable : sysRoleTableList.getData()) {
            R<List<SysRoleTableColumn>> sysRoleTableColumnListR = remoteRoleTableService.getColumnInfoByRoleTableId(sysRoleTable.getRoleTableId(), SecurityConstants.INNER);
            R<SysRoleTableForm> sysRoleTableForm = remoteRoleTableService.getRoleFormInfoByRoleTableId(sysRoleTable.getRoleTableId(), SecurityConstants.INNER);
            R<List<SysRoleTableFormItem>> sysRoleTableFormItemList = new R<>();
            if (null != sysRoleTableForm.getData()) {
                sysRoleTableFormItemList = remoteRoleTableService.getRoleItemInfoByFormId(sysRoleTableForm.getData().getRoleFormId(), SecurityConstants.INNER);
            }
            for (Long userId : userIds) {
                if (null != sysRoleTableColumnListR.getData()) {
                    for (SysRoleTableColumn sysRoleTableColumn : sysRoleTableColumnListR.getData()) {
                        SysUserTableColumn sysUserTableColumn = new SysUserTableColumn();
                        BeanUtils.copyProperties(sysRoleTableColumn, sysUserTableColumn);
                        sysUserTableColumn.setUserId(userId);
                        sysUserTableColumn.setColumnId(sysRoleTableColumn.getRoleColumnId());
                        remoteUserTableService.userTableColumnAdd(sysUserTableColumn, SecurityConstants.INNER);
                    }
                }
                if (null != sysRoleTableFormItemList.getData()) {
                    for (SysRoleTableFormItem sysRoleTableFormItem : sysRoleTableFormItemList.getData()) {
                        SysUserTableFormItem sysUserTableFormItem = new SysUserTableFormItem();
                        BeanUtils.copyProperties(sysRoleTableFormItem, sysUserTableFormItem);
                        sysUserTableFormItem.setUserId(userId);
                        sysUserTableFormItem.setItemId(sysRoleTableFormItem.getRoleItemId());
                        remoteUserTableService.userTableFormItemAdd(sysUserTableFormItem, SecurityConstants.INNER);
                    }
                }
            }
        }
    }

    /**
     * 通过用户ID和菜单id查询 用户对该功能拥有的角色
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<SysRole> selectUserMenuRoles(Long userId) {
        return roleMapper.selectUserMenuRoles(userId);
    }

    /**
     * 导出
     *
     * @param response
     * @param params
     */
    @Override
    public void export(HttpServletResponse response, JSONObject params) {
        Exceel exceel = JSON.toJavaObject(params, Exceel.class);
        PageQuery pageQuery = params.toJavaObject(PageQuery.class);
        //导出方式（current 当前页, selected 选择, all 所有）
        List<SysRole> list = new ArrayList<>();
        if (exceel.getMode().equals("current")) {
            IPage<SysRole> iPage = roleMapper.selectRolePage(pageQuery.build(), new SysRole());
            list = iPage.getRecords();
        } else if (exceel.getMode().equals("selected") && !exceel.getIds().isEmpty()) { //选择导出（选择了选择导出并且选择了数据）
            list = roleMapper.selectVoBatchIds(exceel.getIds());
        } else {
            SysRole sysRole = JSON.parseObject(String.valueOf(exceel.getQuery()), SysRole.class);
            list = roleMapper.selectRoleList(sysRole);
        }
        String sheetName = exceel.getFilename().equals(null) ? "角色数据" : exceel.getSheetName();
        Set<String> column = Arrays.stream(exceel.getFields().stream().map(m -> m.getField()).collect(Collectors.toList()).stream().toArray(String[]::new)).collect(Collectors.toSet());
        ExcelUtil.exportExcel(list, sheetName, SysRole.class, response, column);
    }
}
